package com.leo.erp.service.impl;

import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leo.erp.dao.OrgaUserRelMapper;
import com.leo.erp.dao.UserDao;
import com.leo.erp.dao.UserMapper;
import com.leo.erp.dto.UserExecution;
import com.leo.erp.entity.OrgaUserRel;
import com.leo.erp.entity.User;
import com.leo.erp.enums.UserStateEnum;
import com.leo.erp.service.LogService;
import com.leo.erp.service.TenantService;
import com.leo.erp.service.UserBusinessService;
import com.leo.erp.service.UserService;
import com.leo.erp.util.GlobalRuntimeException;
import com.leo.erp.util.Tools;
import com.leo.erp.util.TreeNodeEx;

@Service
public class UserServiceImpl implements UserService{
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserDao userDao;
	@Autowired
	private UserBusinessService userBusinessService;
	@Autowired
	private TenantService tenantService;
	@Autowired
	private LogService logService;
	@Autowired
	private OrgaUserRelMapper orgaUserRelMapper;

	
	@Override
	public UserExecution checkUserNameAndLoginName(String userName, String loginName, String password) {
		List<User> list = null;
		UserExecution ue = new UserExecution();
		//检查登陆名
		if(loginName != null && loginName != "") {
			//限制登陆名admin
			if(loginName.equals("admin")) {
				ue.setState(UserStateEnum.LOGINNAME_LIMIT.getState());//此登陆名限制使用:6
				return ue;
			}else {
				QueryWrapper<User> queryWrapper = new QueryWrapper<>();
				if(loginName != null && loginName != "") {
					queryWrapper.eq("loginName", loginName);
				}	
				list = userMapper.selectList(queryWrapper);
				if(list != null && list.size() > 0) {
					//该登陆名已在
					ue.setState(UserStateEnum.LOGINNAME_EXIST.getState());//登陆名已存在:4
					return ue;
				}else {
					ue.setState(UserStateEnum.SUCCESS.getState());
				}
			}	
		}
		//检查用户名
		if(userName != null && userName != "") {
			//限制登陆名admin
			if(userName.equals("admin")) {
				ue.setState(UserStateEnum.USERNAME_LIMIT.getState());//此登陆名限制使用:7
				return ue;
			}else {
				QueryWrapper<User> queryWrapper = new QueryWrapper<>();
				queryWrapper.eq("userName", userName);
				list = userMapper.selectList(queryWrapper);
				if(list != null && list.size() > 0) {
					//该用户名已在
					ue.setState(UserStateEnum.USERNAME_EXIST.getState());//用户名已存在:5
					return ue;
				}else {
					ue.setState(UserStateEnum.SUCCESS.getState());
				}
			}		
		}	
		return ue;
	}

	@Override
	@Transactional
	public UserExecution registerUser(User user, Integer manageRoleId, HttpServletRequest request) throws GlobalRuntimeException{
		UserExecution returnUe = new UserExecution();
		int result = 0;
		try {
			user.setPassword(Tools.md5Encryp(user.getPassword()));//MD5加密
			user.setIsSystem(0);
			if(user.getIsManager() <= 0) {
				user.setIsManager(0);//用户不是管理员
			}
			user.setStatus(0);//用户状态 0：正常，1：删除，2封禁			
			result = userMapper.insert(user);//插入数据
			UserExecution ue = getUserByLoginName(user.getLoginName());
			int userId = ue.getUser().getUserId();
			user.setUserId(userId);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		//更新租户id
		User newUser = new User();
		newUser.setUserId(user.getUserId());
		newUser.setTenantId(user.getUserId());
		userMapper.updateById(newUser);
		//存入session
		request.getSession().setAttribute("user", newUser);
		
		//新增用户与角色的关系
		JSONObject ubObj = new JSONObject();
		ubObj.put("type", "UserRole");
		ubObj.put("keyId", user.getUserId());
		JSONArray ubArr = new JSONArray();
		ubArr.add(manageRoleId);
		ubObj.put("value", ubArr.toString());
		userBusinessService.insertUserBusiness(ubObj.toString(), ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
		//创建租户信息
		JSONObject tenantObj = new JSONObject();
		tenantObj.put("tenantId", user.getUserId());
		tenantObj.put("loginName", user.getLoginName());
		String param = tenantObj.toJSONString();
		tenantService.insertTenant(param, request);
		if(result > 0) {
			returnUe.setState(UserStateEnum.SUCCESS.getState());
			returnUe.setUser(user);
		}
		
		return returnUe;
	}

	@Override
	public List<User> getUserList(Wrapper<User> queryWrapper) {
		return userMapper.selectList(queryWrapper);
	}
	
	
	
	@Override
	public UserExecution validateUser(String loginName, String password) {
		//默认是可以登陆的
		List<User> list = null;
		int status = 0;//状态,0:正常
		try {
			QueryWrapper<User> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("loginName", loginName);
			queryWrapper.eq("status", status);
			list = userMapper.selectList(queryWrapper);
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		if(list.size() == 0) {
			return new UserExecution(UserStateEnum.USER_NOT_EXIST);
		}
		
		try {
			QueryWrapper<User> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("loginName", loginName);
			queryWrapper.eq("password", Tools.md5Encryp(password));
			queryWrapper.eq("status", status);
			list = userMapper.selectList(queryWrapper);
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		if(list.size() == 0) {
			return new UserExecution(UserStateEnum.USER_PASSWORD_ERROR);
		}
		
		return new UserExecution(UserStateEnum.SUCCESS);
	}

	@Override
	public UserExecution getUserByLoginName(String loginName) {
		List<User> list = null;
		int status = 0;//状态,0:正常
		try {
			QueryWrapper<User> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("loginName", loginName);
			queryWrapper.eq("status", status);
			list = userMapper.selectList(queryWrapper);
		}catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		UserExecution ue = new UserExecution();
		User user = null;
		if(list != null && list.size() > 0) {
			user = list.get(0);
			ue.setUser(user);
			ue.setState(UserStateEnum.SUCCESS.getState());
		}	
		return ue;
	}

	@Override
	public UserExecution deleteUser(int userId) {
		UserExecution ue = new UserExecution();
		
		try {
			int effectedNum = userMapper.deleteById(userId);
			if(effectedNum > 0) {
				logService.insertLog("用户", "删除", ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
				ue.setState(UserStateEnum.SUCCESS.getState());
			}else {
				ue.setState(UserStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return ue;
	}

	@Override
	public UserExecution countUser(String userName, String loginName) {
		UserExecution ue = new UserExecution();
		List<User> list = null;
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		//判断空值
		if(userName != null && userName != "") {
			queryWrapper.like("userName", userName);
		}
		if(loginName != null && loginName != "") {
			queryWrapper.like("loginName", loginName);
		}
		try {
			list = userMapper.selectList(queryWrapper);
			if(list.size() > -1) {
				ue.setCount(list.size());
				ue.setState(UserStateEnum.SUCCESS.getState());
			}else {
				ue.setState(UserStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		return ue;
	}

	@Override
	public UserExecution addUserAndOrgUserRel(User user) throws GlobalRuntimeException{
		UserExecution ue = new UserExecution();
		if("admin".equals(user.getLoginName())) {
			ue.setState(UserStateEnum.LOGINNAME_LIMIT.getState());//6
			ue.setStateInfo(UserStateEnum.LOGINNAME_LIMIT.getStateInfo());
			return ue;
		}
		if("admin".equals(user.getUserName())){
			ue.setState(UserStateEnum.USERNAME_LIMIT.getState());//7
			ue.setStateInfo(UserStateEnum.USERNAME_LIMIT.getStateInfo());
			return ue;
		}
		
		//检查用户名和登陆名
		UserExecution checkUserAndLogin = checkUserNameAndLoginName(user.getUserName(), user.getLoginName(), user.getPassword());
		if(checkUserAndLogin.getState() == UserStateEnum.LOGINNAME_EXIST.getState()) {
			ue.setState(UserStateEnum.LOGINNAME_EXIST.getState());
			ue.setStateInfo(UserStateEnum.LOGINNAME_EXIST.getStateInfo());
			return ue;
		}
		if(checkUserAndLogin.getState() == UserStateEnum.USERNAME_EXIST.getState()) {
			ue.setState(UserStateEnum.USERNAME_EXIST.getState());
			ue.setStateInfo(UserStateEnum.USERNAME_EXIST.getStateInfo());
			return ue;
		}
		try {
			if(user.getPassword() != null && user.getPassword() != "") {
				user.setPassword(Tools.md5Encryp(user.getPassword()));
			}else {
				user.setPassword(Tools.md5Encryp("123456"));
			}	
			user.setIsSystem(0);//用户是否系统自带 0、非系统自带，1系统自带
			if(user.getIsManager() > -1) {
				user.setIsManager(1);//0管理者,1员工
			}
			user.setStatus(0);
			//获取session
			HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
			User uu = (User) request.getSession().getAttribute("user");
			user.setTenantId(uu.getUserId());
			
			int effectedNum = userMapper.insert(user);
			if(effectedNum > 0) {
				logService.insertLog("用户", "新增", ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
				ue.setState(UserStateEnum.SUCCESS.getState());
				if(user.getOrgaId() < 0 ) {
					//如果没有选择机构,就不建立机构和用户的关联关系
					return ue;
				}else {
					//新增用户和机构关联关系
					OrgaUserRel oul = new OrgaUserRel();
					//机构id
					oul.setOrgaId(user.getOrgaId());
					//用户id,根据用户名查询id
					UserExecution userFindId = getUserByLoginName(user.getLoginName());
					int userId = userFindId.getUser().getUserId();
					oul.setUserId(userId);
					//用户在机构中的排序
					oul.setUserBlngOrgaDsplSeq(user.getUserBlngOrgaDsplSeq());
					
					orgaUserRelMapper.insert(oul);//插入数据
				}
			}else {
				ue.setState(UserStateEnum.OFFLINE.getState());
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}	
		return ue;
	}

	@Override
	public UserExecution resetPwd(String md5Pwd, int id) {
		//先获取用户信息
		User user = userMapper.selectById(id);
		
		user.setPassword(md5Pwd);
		
		UserExecution ue = new UserExecution();
		try {
			int effectedNum = userMapper.updateById(user);
			if(effectedNum > 0) {
				logService.insertLog("用户", "修改id=" + user.getUserId() + "的密码", ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
				ue.setState(UserStateEnum.SUCCESS.getState());
			}else {
				ue.setState(UserStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return ue;
	}

	@Override
	public UserExecution updateUserAndOrgUserRel(User user) {
		UserExecution ue = new UserExecution();
		if("admin".equals(user.getLoginName())) {
			ue.setState(UserStateEnum.LOGINNAME_LIMIT.getState());//6
			ue.setStateInfo(UserStateEnum.LOGINNAME_LIMIT.getStateInfo());
			return ue;
		}
		if("admin".equals(user.getUserName())){
			ue.setState(UserStateEnum.USERNAME_LIMIT.getState());//7
			ue.setStateInfo(UserStateEnum.USERNAME_LIMIT.getStateInfo());
			return ue;
		}
		
		//检查用户名和登陆名
		UserExecution checkUserAndLogin = checkUserNameAndLoginName(user.getUserName(), null, user.getPassword());
		if(checkUserAndLogin.getState() == UserStateEnum.USERNAME_EXIST.getState()) {
			ue.setState(UserStateEnum.USERNAME_EXIST.getState());
			ue.setStateInfo(UserStateEnum.USERNAME_EXIST.getStateInfo());
			return ue;
		}
		
		try {
			//先取出user的tenantId
			User u = userMapper.selectById(user.getUserId());
			int tenantId = u.getTenantId();
			user.setTenantId(tenantId);
			
			//更新用户信息
			int effectedNum = userMapper.updateById(user);
			if(effectedNum > 0) {
				logService.insertLog("用户", "修改了id=" + user.getUserId() + "的信息", ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
				
				if(user.getOrgaId() <= 0) {
					//如果没有选择机构，就不建机构和用户的关联关系
					return ue;
				}else {
					//更新用户和机构关联关系
					QueryWrapper<OrgaUserRel> query = new QueryWrapper<>();
					query.eq("userId", user.getUserId());
					List<OrgaUserRel> list = orgaUserRelMapper.selectList(query);
					OrgaUserRel oul = list.get(0);//获取信息
					
					//机构id
					oul.setOrgaId(user.getOrgaId());
					//用户id
					oul.setUserId(user.getUserId());
					//用户在机构中的排序
					oul.setUserBlngOrgaDsplSeq(user.getUserBlngOrgaDsplSeq());
					//更新时间
					oul.setUpdateTime(new Date());
					
					if(oul.getOrgaUserRelId() > 0) {
						//已存在机构和用户的关联关系，更新
						orgaUserRelMapper.updateById(oul);
					}else {
						//不存在机构和用户的关联关系，新建
						orgaUserRelMapper.insert(oul);
					}
					
				}
				
				ue.setState(UserStateEnum.SUCCESS.getState());
			}else {
				ue.setState(UserStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return ue;
	}

	@Override
	public UserExecution getList(String userName, String loginName, int currentPage, int pageSize) {
		UserExecution ue = new UserExecution();
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		
		//判断
		if(userName != null && userName != "") {
			queryWrapper.like("userName", userName);
		}
		if(loginName != null && loginName != "") {
			queryWrapper.like("loginName", loginName);
		}
		
		Page<User> page = new Page<>(currentPage, pageSize);//分页查询
		IPage<Map<String, Object>> iPage = userMapper.selectMapsPage(page, queryWrapper);
		if(iPage.getRecords().size() > 0) {
			ue.setState(UserStateEnum.SUCCESS.getState());
			ue.setPages(page.getPages());//总页数
			ue.setTotal(iPage.getTotal());//总记录数
			ue.setUserPageList(iPage.getRecords());
		}else{
			ue.setState(UserStateEnum.OFFLINE.getState());
		}
		
		return ue;
	}

	@Override
	public UserExecution getAllList() {
		UserExecution ue = new UserExecution();
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("status", 0);
		try {
			List<User> list = userMapper.selectList(queryWrapper);
			if(list.size() > -1) {
				ue.setState(UserStateEnum.SUCCESS.getState());
				ue.setUserList(list);
			}else {
				ue.setState(UserStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		return ue;
	}

	@Override
	public UserExecution getUserNameById(int userId) {
		UserExecution ue = new UserExecution();
		User user = userMapper.selectById(userId);
		if(user != null) {
			ue.setState(UserStateEnum.SUCCESS.getState());
			ue.setUser(user);
		}else {
			ue.setState(UserStateEnum.OFFLINE.getState());
		}
		return ue;
	}

	@Override
	public List<TreeNodeEx> getOrganizationUserTree() {
		List<TreeNodeEx> list = null;
		try {
			list = userDao.getNodeTree();
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public UserExecution getUserById(int userId) {
		UserExecution ue = new UserExecution();
		User user = userMapper.selectById(userId);
		if(user != null) {
			ue.setState(UserStateEnum.SUCCESS.getState());
			ue.setUser(user);
		}else {
			ue.setState(UserStateEnum.OFFLINE.getState());
		}	
		return ue;
	}
	
}
